﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved All Rights Reserved All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.ServiceModel;
using FinPlusBaseCore;
using FinPlusAssembler;
using FinPlusInterfaces;

namespace FinPlusConnData
{
    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
    public class RequestCallback : IPodCallback
    {
        private ServiceConn _serviceConn;

        public  RequestCallback(ServiceConn conn){_serviceConn = conn;}

        public void DispatchPod(Env env, string serviceKey, string linkedId, IEnumerable<Bean> value, ChangeType changeType)
        {
            try
            {
                if (!linkedId.Equals(_serviceConn.LinkedId)) 
                    throw new Exception();

                var f = new Pod(value);

                if (changeType == ChangeType.Removed)
                    _serviceConn.Remove(f.Id);
                else if (changeType == ChangeType.New)
                    _serviceConn.Add(f);
            }
            catch (Exception e)
            {
                Level.Error.Log(e.Message, e);
                throw new FaultException(e.Message);
            }
        }

        public void DispatchBean(Env env, string serviceKey, string linkedId, int id, Bean value, ChangeType changeType)
        {
            try
            {
                if (!linkedId.Equals(_serviceConn.LinkedId))
                    throw new ServiceConnException(string.Format("Service conn {0} does not match {1} not open", linkedId, _serviceConn.LinkedId));

                _serviceConn.Update(id, value, changeType);
            }
            catch (Exception e)
            {
                Level.Error.Log(e.Message, e);
                throw new FaultException(e.Message);
            }
        }

        public void DispatchCompleted(Env env, string serviceKey, string linkedId)
        {
            try
            {
                if (!linkedId.Equals(_serviceConn.LinkedId))
                    throw new Exception();

                if (_serviceConn.LinkedId.Equals(linkedId))
                    _serviceConn.HasCompleted = true;
            }
            catch (Exception e)
            {
                Level.Error.Log(e.Message, e);
                throw new FaultException(e.Message);
            }
        }
    }
}
